package cn.rcth.controller;

import cn.rcth.base.constants.BaiseConstants;
import cn.rcth.base.domain.Order;
import cn.rcth.base.domain.OrderProduct;
import cn.rcth.base.domain.Product;
import cn.rcth.base.msg.ResultMsg;
import cn.rcth.base.msg.WechatConfig;

import cn.rcth.base.serivce.IOrderProductSerivce;
import cn.rcth.base.serivce.IOrderSerivce;
import cn.rcth.base.serivce.IPaySerivce;
import cn.rcth.base.serivce.IProductSerivce;
import cn.rcth.base.util.HttpRequest;
import cn.rcth.base.util.PayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
public class PayController {

    @Autowired
    private IOrderSerivce orderSerivce;

    @Autowired
    private IPaySerivce paySerivce;


    @Autowired
    private IProductSerivce productSerivce;


    @RequestMapping(value = "/wxPaysss", method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg wxPay(HttpServletRequest request, Long orderId, String openId) {
        //获取当前用户ip地址
        String spbill_create_ip = HttpRequest.getIpAddr(request);
        //微信支付
        ResultMsg resultMsg = paySerivce.wxPay(orderId, spbill_create_ip, openId);
        return resultMsg;
    }

    //这里是支付回调接口，微信支付成功后会自动调用
    @RequestMapping(value = "/wxNotify", method = RequestMethod.POST)
    @ResponseBody
    public void wxNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String line = null;
        String xmlString = null;
        BufferedReader reader = request.getReader();
        StringBuffer stringBuffer = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            stringBuffer.append(line);
        }
        xmlString = stringBuffer.toString();
        request.getReader().close();
        System.out.println("微信回调的数据" + xmlString);
        String resXml = "";
        Map map = PayUtil.doXMLParse(xmlString);
        String returnCode = (String) map.get("return_code");
        if ("SUCCESS".equals(returnCode)) {
            //验证签名是否正确
           Map<String, String> validParams = PayUtil.paraFilter(map);  //回调验签时需要去除sign和空值参数
            String prestr = PayUtil.createLinkString(validParams);
            //根据微信官网的介绍，此处不仅对回调的参数进行验签，还需要对返回的金额与系统订单的金额进行比对等
            if (PayUtil.verify(prestr, (String) map.get("sign"), WechatConfig.key, "utf-8")) {
                /**此处添加自己的业务逻辑代码start**/
                //支付成功回调
                String sn = (String) map.get("out_trade_no");
                //根据订单号查询订单 并修改订单状态
                Order order = orderSerivce.selectOrderBySn(sn);
                List<OrderProduct> orderProducts = order.getOrderProducts();
                for (OrderProduct orderProduct : orderProducts) {
                    Long productId = orderProduct.getProductId();
                    Integer count = orderProduct.getCount();
                    if (count != null){
                        Product product = productSerivce.selectProduct(productId);
                        product.setSales(product.getOnSales() + count);
                        product.setModifyTime(new Date());
                        product.setModifyId(order.getUserId());
                        productSerivce.updateProduct(product);
                    }
                }
                if (order.getStatus().equals(BaiseConstants.ORDER_TO_BE_PAID)) {
                    //修改订单状态
                    order.setStatus(BaiseConstants.ORDER_PAID);
                    Date date = new Date();
                    order.setPoyTime(date);
                    order.setModifyTime(date);
                    order.setModifyId(order.getUserId());
                    //保存
                    orderSerivce.updateOrder(order);
                }
                //注意要判断微信支付重复回调，支付成功后微信会重复的进行回调
                /**此处添加自己的业务逻辑代码end**/
                //通知微信服务器已经支付成功
                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                        + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
            }
        } else {
            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
        }

        BufferedOutputStream out = new BufferedOutputStream(
                response.getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();
    }
}
